﻿using System;
using System.Text;
using System.Collections.Generic;

namespace UtilTools
{
    /// <summary>
    /// 
    /// </summary>
    public class EventBus
    {
        private static EventBus GlobalDispatcher;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objs"></param>
        public delegate void EventHandler(params object[] objs);
        private readonly Dictionary<String, EventHandler> EventListeners = new Dictionary<String, EventHandler>();
        /// <summary>
        /// 
        /// </summary>
        public static EventBus Dispatcher
        {
            get
            {
                if (GlobalDispatcher == null) { GlobalDispatcher = new EventBus(); }
                return GlobalDispatcher;
            }
        }

        /// <summary>
        /// 监听通知
        /// </summary>
        /// <param name="evt"></param>
        /// <param name="handler"></param>
        public void On(String evt, EventHandler handler)
        {
            if (EventListeners.ContainsKey(evt)) { EventListeners[evt] += handler; }
            else { EventListeners.Add(evt, handler); }
        }

        /// <summary>
        /// 发送通知
        /// </summary>
        /// <param name="evt"></param>
        /// <param name="objs"></param>
        public void Emit(String evt, params object[] objs)
        {
            if (EventListeners.ContainsKey(evt)) { EventListeners[evt](objs); }
        }

        /// <summary>
        /// 删除监听
        /// </summary>
        /// <param name="evt"></param>
        /// <param name="handler"></param>
        public void Off(String evt, EventHandler handler)
        {
            if (EventListeners.ContainsKey(evt))
            {
                EventListeners[evt] -= handler;
                if (EventListeners[evt] == null) { EventListeners.Remove(evt); }
            }
        }
    }
}
